package com.gateway.video.rtsp.server.bootstrap;

import com.gateway.video.rtsp.server.channel.InitChannel;
import com.gateway.video.rtsp.server.config.VideoServerConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URI;

@Slf4j
public class VideoServerBootstrap extends ServerBootstrap implements InitializingBean {
    @Autowired
    private EventLoopGroup group;

    @Autowired
    private VideoServerConfig videoConfig;

    @Autowired
    private InitChannel initChannel;

    @Override
    public void afterPropertiesSet() throws Exception {
        group(group);
        childOption(ChannelOption.TCP_NODELAY, true);
        childOption(ChannelOption.SO_REUSEADDR, true);
        channel(NioServerSocketChannel.class);
        childHandler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                initChannel.configuer(channel);
            }
        });

        var bind = URI.create(videoConfig.getBind());
        bind(bind.getHost(), bind.getPort()).addListener(future -> {
            if (future.isSuccess()) {
                if (log.isInfoEnabled()) {
                    log.info("gateway video server has bind address, {}", bind);
                }
            }
        }).sync();
    }
}
